import { useState, useEffect } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Typography,
  Pagination,
  CircularProgress,
  Alert,
} from '@mui/material';
import { Delete as DeleteIcon, GetApp as GetAppIcon } from '@mui/icons-material';
import { TorrentService, TorrentInfo } from '../services/TorrentService';
import { useAuth } from '../../auth/AuthContext';

const formatSize = (bytes: number): string => {
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  if (bytes === 0) return '0 B';
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`;
};

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleString('zh-CN');
};

const TorrentList = () => {
  const [torrents, setTorrents] = useState<TorrentInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [pageSize] = useState(10);
  
  const { user } = useAuth();

  const fetchTorrents = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await TorrentService.getTorrentList(page, pageSize);
      setTorrents(response.torrents);
      setTotalPages(Math.ceil(response.total / pageSize));
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取种子列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTorrents();
  }, [page]);

  const handleDownload = async (torrentId: string, torrentName: string) => {
    try {
      const blob = await TorrentService.downloadTorrent(torrentId);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = torrentName;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      setError(err instanceof Error ? err.message : '下载失败');
    }
  };

  const handleDelete = async (torrentId: string) => {
    if (!window.confirm('确定要删除这个种子文件吗？')) return;
    
    try {
      await TorrentService.deleteTorrent(torrentId);
      fetchTorrents(); // 重新加载列表
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除失败');
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" p={3}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ width: '100%' }}>
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>名称</TableCell>
              <TableCell align="right">大小</TableCell>
              <TableCell align="right">上传者</TableCell>
              <TableCell align="right">上传时间</TableCell>
              <TableCell align="right">下载次数</TableCell>
              <TableCell align="right">做种数</TableCell>
              <TableCell align="right">下载数</TableCell>
              <TableCell align="right">操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {torrents.map((torrent) => (
              <TableRow key={torrent.id}>
                <TableCell component="th" scope="row">
                  {torrent.name}
                </TableCell>
                <TableCell align="right">{formatSize(torrent.size)}</TableCell>
                <TableCell align="right">{torrent.uploaderName}</TableCell>
                <TableCell align="right">{formatDate(torrent.createdAt)}</TableCell>
                <TableCell align="right">{torrent.downloadCount}</TableCell>
                <TableCell align="right">{torrent.seeders}</TableCell>
                <TableCell align="right">{torrent.leechers}</TableCell>
                <TableCell align="right">
                  <IconButton
                    onClick={() => handleDownload(torrent.id, torrent.name)}
                    size="small"
                    title="下载"
                  >
                    <GetAppIcon />
                  </IconButton>
                  {user && (user.id === torrent.uploaderId || user.role === 'admin') && (
                    <IconButton
                      onClick={() => handleDelete(torrent.id)}
                      size="small"
                      color="error"
                      title="删除"
                    >
                      <DeleteIcon />
                    </IconButton>
                  )}
                </TableCell>
              </TableRow>
            ))}
            {torrents.length === 0 && (
              <TableRow>
                <TableCell colSpan={8} align="center">
                  <Typography variant="body2" color="text.secondary">
                    暂无种子文件
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
        <Pagination
          count={totalPages}
          page={page}
          onChange={(_, value) => setPage(value)}
          color="primary"
        />
      </Box>
    </Box>
  );
};

export default TorrentList;